package controllers

import (
	"2302a_shop2/cache"
	"2302a_shop2/models"
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type ShopController struct {
	beego.Controller
}

func (c *ShopController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var shops []models.Shop

	models.DB.Find(&shops)
	key := fmt.Sprintf("shops_list_%s", shops)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData != "" {
		json.Unmarshal([]byte(cacheData), &shops)
	} else {
		jsonData, _ := json.Marshal(shops)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*1)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mes":  "查询成功",
		"data": shops,
	}
	c.ServeJSON()
	return
}
func (c *ShopController) Update() {

	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	description := c.GetString("description")
	stock, _ := c.GetInt("stock")

	shops := models.Shop{
		Name:        name,
		Price:       price,
		Description: description,
		Stock:       stock,
	}
	key := fmt.Sprintf("shops_ID_%d", shops.ID)
	jsonData, _ := json.Marshal(shops)
	cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*1)
	models.DB.Updates(&shops)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mes":  "修改成功",
		"data": shops,
	}
	c.ServeJSON()
	return
}
func (c *ShopController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var shops []models.Shop
	id, _ := c.GetInt("id")
	models.DB.Where("id=?", id).Delete(&shops)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mes":  "删除成功",
		"data": shops,
	}
	c.ServeJSON()
	return
}
